package org.knife.springbootlearn.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 使用{@link UserDetailsService}来实现自定义的登陆认证
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2021年12月02日 星期四 9:37 上午
 * @description
 * @since 1.0
 */
@Configuration
public class MyCustomerWebSecurityConfigureAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 只要通过验证就可以访问所有的请求
        // authorizeRequests方法限定只对签名成功的用户请求
        // anyRequest方法限定所有请求
        // authenticated方法对所有签名成功的用户允许方法
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
        // formLogin代表使用spring security默认的登陆页面
        http.formLogin();
        // httpBasic方法说明启用http基础认证
        // .csrf().disable()暂时不知道如何解决跨域token问题
        http.csrf().disable().httpBasic();
    }
}
